<template>
  <create-view
    :loading="loading"
    :body-style="{ height: '100%'}">
    <flexbox
      direction="column"
      align="stretch"
      class="crm-create-container">
      <flexbox class="crm-create-header">
        <div style="flex:1;font-size:17px;color:#333;">{{ title }}</div>
        <img
          class="close"
          src="@/assets/img/task_close.png"
          @click="hidenView" >
      </flexbox>
      <div class="crm-create-flex">
        <create-sections title="基本信息">
<!--          <div v-if="psiType == 'salesLeave'" style="background-color: #e5f7ff;font-size: 13px;margin: 5px 10px;">-->
<!--            <span>关联合同模块</span>-->
<!--          </div>-->
          <flexbox
            direction="column"
            align="stretch">
            <div class="crm-create-body">
              <el-form
                ref="crmForm"
                :model="crmForm"
                label-position="top"
                class="crm-create-box">
                <el-form-item
                  v-for="(item, index) in crmForm.crmFields"
                  :key="item.key"
                  :prop="'crmFields.' + index + '.value'"
                  :class="{ 'crm-create-block-item': item.showblock, 'crm-create-item': !item.showblock }"
                  :rules="crmRules[item.key]"
                  :style="{'padding-left': getPaddingLeft(item, index), 'padding-right': getPaddingRight(item, index)}">
                  <div
                    slot="label"
                    style="display: inline-block;">
                    <div style="margin:5px 0;font-size:12px;word-wrap:break-word;word-break:break-all;">
                      {{ item.data.name }}
                      <span style="color:#999;">
                        {{ item.data.inputTips ? '（'+item.data.inputTips+'）':'' }}
                      </span>
                    </div>
                  </div>
                  <!-- 员工 和部门 为多选（radio=false）  relation 相关合同商机使用-->
                  <component
                    :is="item.data.formType | typeToComponentName"
                    :value="item.value"
                    :index="index"
                    :item="item"
                    :relation="item.relation"
                    :radio="false"
                    :disabled="item.disabled"
                    :isonly="isOnlyRadio"
                    @value-change="fieldValueChange"/>
                </el-form-item>
              </el-form>
            </div>
          </flexbox>
        </create-sections>
        <create-sections
          v-if="psiType == 'product'"
          title="规格信息">
          <specificine
            ref="moreSpec"
            :action="action"
            :storehouse-vel="getStorehouse"
            @getSpecValue="SpecValue"/>
        </create-sections>
        <create-sections
          v-if="showProductImg"
          title="产品信息">
          <store-product
            ref="storeProductCom"
            :action="action"
            :psi-type="psiType"
            :isenter="isenter"
            :isleave="isLeave"
            :storehouse="searchProdutHouseId"></store-product>
        </create-sections>
        <create-sections
          v-if="showExamine"
          title="审核信息">
          <div
            v-if="examineInfo.examineType===1 || examineInfo.examineType===2"
            slot="header"
            class="examine-type">{{ examineInfo.examineType===1 ? '固定审批流' : '授权审批人' }}</div>
          <create-examine-info
            ref="examineInfo"
            :types="'crm_' + psiType"
            :types-id="action.id"
            @value-change="examineValueChange"/>
        </create-sections>
      </div>
      <div class="handle-bar">
        <el-button
          class="handle-button"
          @click.native="hidenView">取消</el-button>
        <!--        <el-button-->
        <!--          v-if="psiType=='customer' && action.type == 'save'"-->
        <!--          class="handle-button"-->
        <!--          type="primary"-->
        <!--          @click.native="saveField(true)">保存并新建联系人</el-button>-->
        <el-button
          v-if="showDraft"
          class="handle-button"
          type="primary"
          plain
          @click.native="saveDraftField()">保存草稿</el-button>
        <el-button
          class="handle-button"
          type="primary"
          @click.native="saveField(false)">{{ sureBtnTitle }}</el-button>
      </div>
      <duplicate-check
        v-if="showDuplicateCheck"
        :customerValue='customerName'
        @hiden-view="showDuplicateCheck=false"/>
    </flexbox>
  </create-view>
</template>
<script type="text/javascript">
import { mapGetters } from 'vuex'
import psiTypeModel from '@/views/psimanagement/model/psiTypeModel'
import CreateView from '@/components/CreateView'
import CreateSections from '@/components/CreateSections'
import CreateExamineInfo from '@/components/Examine/CreateExamineInfo'
import { filedGetField, filedValidates } from '@/api/psimanagement/common'
import { psiStorehouseSave } from '@/api/psimanagement/storehouse'
import { psiProductSave } from '@/api/psimanagement/product'
import { psiEnterLeaveStockSave, psiSalesLeaveContactsByNum, psiEnterLeaveStorageIndex } from '@/api/psimanagement/enter-storage'
import {
  crmBusinessProduct // 商机下产品
} from '@/api/customermanagement/business'
import {
  crmCustomerQueryContacts
} from '@/api/customermanagement/customer' // 借用出库时的客户信息
import {
  regexIsCRMNumber,
  regexIsCRMMoneyNumber,
  regexIsCRMMobile,
  regexIsCRMEmail,
  objDeepCopy
} from '@/utils'

import { isArray } from '@/utils/types'

import {
  XhInput,
  XhTextarea,
  XhSelect,
  XhMultipleSelect,
  XhDate,
  XhDateTime,
  XhUserCell,
  XhStructureCell,
  XhFiles,
  CrmRelativeCell,
  XhProuctCate,
  XhProduct,
  XhCustomer,
  XhBusinessStatus,
  XhCustomerAddress,
  XhReceivablesPlan // 回款计划期数
} from '@/components/CreateCom'

import specificine from '../../../components/CreateCom/specificine'
import XhPicture from '../../../components/CreateCom/XhPicture'
import StoreProduct from '../../../components/CreateCom/StoreProduct'
import TypeAndMobile from '../../../components/CreateCom/typeAndmobile'
import XhInputSelect from '../../../components/CreateCom/XhInputSelect'
export default {
  name: 'psiCreateView', // 所有新建效果的view
  components: {
    CreateView,
    CreateSections,
    CreateExamineInfo, // 审核信息
    XhInput,
    XhTextarea,
    XhSelect,
    XhMultipleSelect,
    XhDate,
    XhDateTime,
    XhUserCell,
    XhStructureCell,
    XhFiles,
    CrmRelativeCell,
    XhProuctCate,
    XhProduct,
    XhCustomer,
    XhBusinessStatus,
    XhCustomerAddress,
    XhReceivablesPlan,
    specificine,
    XhPicture,
    StoreProduct,
    TypeAndMobile,
    XhInputSelect
  },
  filters: {
    /** 根据type 找到组件 */
    typeToComponentName(formType) {
      if (
        formType == 'text' ||
        formType == 'number' ||
        formType == 'floatnumber' ||
        formType == 'mobile' ||
        formType == 'email'
      ) {
        return 'XhInput'
      } else if (formType == 'textarea') {
        return 'XhTextarea'
      } else if (formType == 'select' || formType == 'business_status') {
        return 'XhSelect'
      } else if (formType == 'checkbox') {
        return 'XhMultipleSelect'
      } else if (formType == 'date') {
        return 'XhDate'
      } else if (formType == 'datetime') {
        return 'XhDateTime'
      } else if (formType == 'user') {
        return 'XhUserCell'
      } else if (formType == 'structure') {
        return 'XhStructureCell'
      } else if (formType == 'file') {
        return 'XhFiles'
      } else if (
        formType == 'contacts' ||
        formType == 'customer' ||
        formType == 'contract' ||
        formType == 'business' ||
        formType == 'storehouse' ||
        formType == 'supplier' ||
        formType == 'customer_all'
      ) {
        return 'CrmRelativeCell'
      } else if (formType == 'category') {
        // 产品类别
        return 'XhProuctCate'
      } else if (formType == 'business_type') {
        // 商机类别
        return 'XhBusinessStatus'
      } else if (formType == 'product') {
        return 'XhProduct'
      } else if (formType == 'map_address') {
        return 'XhCustomerAddress'
      } else if (formType == 'receivables_plan') {
        return 'XhReceivablesPlan'
      } else if (formType == 'customer_contacts') {
        return 'XhCustomer'
      } else if (formType == 'pictures') {
        return 'XhPicture'
      } else if (formType == 'type_phone') {
        return 'TypeAndMobile'
      } else if (
        formType == 'psi_salesLeave_si' ||
        formType == 'finance_purchase_si' ||
        formType == 'psi_borrowLeave_si' ||
        formType == 'psi_repairLeave_si' ||
        formType == 'psi_testLeave_si' ||
        formType == 'psi_otherLeave_si' ||
        formType == 'customer_contact_si' ||
        formType == 'contract_si') {
        return 'XhInputSelect'
      }
    }
  },
  props: {
    // CRM类型
    psiType: {
      type: String,
      default: ''
    },
    /**
     * save:添加、update:编辑(action_id)、read:详情、index:列表
       * relative: 相关 添加(目前用于客户等相关添加) 如果有relativeData 直接合并入上传
     */
    action: {
      type: Object, default: () => {
        return {
          type: 'ave',
          id: '',
          data:{} // 编辑所需信息
        }
      }
    }
  },
  data() {
    return {
      // 标题展示名称
      title: '',
      loading: false,
      saveAndCreate: false, // 保存并新建
      // 自定义字段验证规则
      crmRules: {},
      // 自定义字段信息表单
      crmForm: {
        crmFields: []
      },
      // 审批信息
      examineInfo: {},
      // 数据查重按钮的显示
      showBtnCheck: false,
      showDuplicateCheck: false,
      customerName: '',
      customerValueBiz: '',
      specValueInfo: {},
      getStorehouse: [],
      // 出入库中选择仓库后的ID，需要带入到入库产品中进行产品的筛选
      searchProdutHouseId: '',
      // 产品是否是主产品
      upCodeUniqueFlag: 0,
      productType: 0
    }
  },
  computed: {
    ...mapGetters(['userInfo']),
    // 区分是入库模块还是出库模块
    isenter() {
      if (
        this.psiType == 'salesEnter' ||
        this.psiType == 'purchaseEnter' ||
        this.psiType == 'retrunEnter' ||
        this.psiType == 'repairEnter' ||
        this.psiType == 'testEnter' ||
        this.psiType == 'inventoryProfitEnter' ||
        this.psiType == 'otherEnter'
      ) {
        return true
      }
      return false
    },
    isLeave() {
      if (
        this.psiType == 'salesLeave' ||
        this.psiType == 'borrowLeave' ||
        this.psiType == 'repairLeave' ||
        this.psiType == 'testLeave' ||
        this.psiType == 'inventoryLossLeave' ||
        this.psiType == 'otherLeave'
      ) {
        return true
      }
      return false
    },
    /** 合同 回款 线索下展示审批人信息 */
    showExamine() {
      if (this.isenter || this.isLeave) {
        return true
      }
      return false
    },
    // 草稿按钮
    showDraft() {
      if (this.isenter || this.isLeave) {
        return true
      }
      return false
    },
    sureBtnTitle() {
      if (this.isenter || this.isLeave) {
        return '提交审核'
      }
      return '保存'
    },
    // 是否显示产品信息
    showProductImg() {
      if (this.psiType !== 'product' && this.psiType !== 'storehouse') {
        return true
      }
      return false
    },
    // 仓库选择在出入库的时候为单选
    isOnlyRadio() {
      if (
        this.isenter || this.isLeave
      ) {
        return true
      }
      return false
    }
  },
  watch: {
    psiType: function(value) {
      this.title = this.getTitle()
      this.crmRules = {}
      this.crmForm = {
        crmFields: []
      }
      this.examineInfo = {}
      this.getField()
    }
  },
  mounted() {
    // 获取title展示名称
    document.body.appendChild(this.$el)
    this.title = this.getTitle()
    this.getField()
  },
  destroyed() {
    // remove DOM node after destroy
    if (this.$el && this.$el.parentNode) {
      this.$el.parentNode.removeChild(this.$el)
    }
  },
  methods: {
    // 关联出库单
    rEContent(val) {
      var params = {
        limit: 15,
        page: 1,
        search: val.value,
        type: 41
      }
      psiEnterLeaveStorageIndex(params)
        .then(res => {
          for (let indexp = 0; indexp < this.crmForm.crmFields.length; indexp++) {
            const elementp = this.crmForm.crmFields[indexp]
            if (elementp.key === 'customer_contact_receiver') {
              elementp.value = res.data.list[0].customerContactReceiver
            } else if (elementp.key === 'customer_phone_receiver') {
              elementp.value = res.data.list[0].customerPhoneReceiver
            } else if (elementp.key === 'customer_name_receiver') {
              elementp.value = [{ customerName: res.data.list[0].customerNameReceiverName, customerId: res.data.list[0].customerNameReceiver }]
            }
          }
          this.loading = false
        })
        .catch(() => {
          this.loading = false
        })
    },
    withContract(data) {
      var params = {
        num: data
      }
      psiSalesLeaveContactsByNum(params)
        .then(res => {
          for (let index = 0; index < this.crmForm.crmFields.length; index++) {
            const element = this.crmForm.crmFields[index]
            if (element.key === 'contract_customer_name') {
              element['value'] = res.data.customerName
            } else if (element.key === 'customer_name_receiver') {
              element['value'] = [{ customerName: res.data.customerName, customerId: res.data.customerId }]
            } else if (element.key === 'contract_customer_address') {
              element['value'] = res.data.address
            } else if (element.key === 'contract_customer_detail_add') {
              element['value'] = res.data.detailAddress
            } else if (element.key === 'contract_customer_phone') {
              element['value'] = []
              for (var i = 0; i < res.data.listContacts.length; i++) {
                element['value'].push({ mobileNum: res.data.listContacts[i].mobile, typeVue: '电话' })
              }
            } else if (element.key === 'customer_phone_receiver') {
              element['value'] = res.data.listContacts[0].mobile
            } else if (element.key === 'customer_contact_receiver') {
              element['value'] = [{ name: res.data.listContacts[0].name, contactsId: res.data.listContacts[0].contactsId }]
            } else if (element.key === 'map_address') {
              element['value'] = { address: res.data.address, detailAddress: res.data.detailAddress, location: res.data.location, lng: res.data.lng, lat: res.data.lat }
            }
          }
          this.loading = false
        })
        .catch(() => {
          this.loading = false
        })
    },
    // 规格信息获取更新
    SpecValue(data) {
      this.getStorehouse = data
    },
    // 审批信息值更新
    examineValueChange(data) {
      this.examineInfo = data
    },
    // 字段的值更新
    fieldValueChange(data) {
      var item = this.crmForm.crmFields[data.index]
      item.value = data.value
      this.showBtnCheck = false
      // 出入库
      if (this.isenter || this.isLeave) {
        if (item.data.formType == 'storehouse') {
          for (let index = 0; index < this.crmForm.crmFields.length; index++) {
            const element = this.crmForm.crmFields[index]
            if (element.key === 'storehouse_id') {
              if (element.value[0]) {
                this.searchProdutHouseId = element.value[0].storehouseId
              } else {
                this.searchProdutHouseId = ''
              }
            }
          }
        } else if (item.data.formType == 'supplier') {
          for (let index = 0; index < this.crmForm.crmFields.length; index++) {
            const element = this.crmForm.crmFields[index]
            if (element.key === 'customer_contact_receiver') {
              element.value = item.value[0].contactPerson
            } else if (element.key === 'customer_phone_receiver') {
              // var valueArry = JSON.parse(item.value[0].供应商电话)
              // var valueCont = ''
              // for (var i = 0; i < valueArry.length; i++) {
              //   valueCont = valueCont + valueArry[i].typeVue + ':' + valueArry[i].mobileNum + ' , '
              // }
              element.value = item.value[0].联系人电话
            }
          }
        } else if (
          item.data.formType === 'psi_salesLeave_si' ||
          item.data.formType === 'finance_purchase_si' ||
          item.data.formType === 'psi_borrowLeave_si' ||
          item.data.formType === 'psi_repairLeave_si' ||
          item.data.formType === 'psi_testLeave_si' ||
          item.data.formType === 'psi_otherLeave_si' ||
          item.data.formType == 'contract_si'
        ) {
          if (typeof data.value == 'string') {
          } else {
            var isDelect = false
            if (data.value.length > 0) {
              isDelect = false
            } else {
              isDelect = true
            }
            for (let index = 0; index < this.crmForm.crmFields.length; index++) {
              const element = this.crmForm.crmFields[index]
              if (element.key === 'customer_contact_receiver') {
                element.value = !isDelect ? [{ name: item.value[0].customerContactReceiver, contactsId: item.value[0].customerContactIdReceiver }] : []
              } else if (element.key === 'customer_phone_receiver') {
                element.value = !isDelect ? item.value[0].customerPhoneReceiver : ''
              } else if (element.key === 'customer_name_receiver') {
                if (item.data.formType === 'psi_borrowLeave_si') {
                  element.value = !isDelect ? [{ customerName: item.value[0].customerNameReceiverName, customerId: item.value[0].customerNameReceiver }] : []
                } else {
                  element.value = !isDelect ? [{ customerName: item.value[0].customerName, customerId: item.value[0].customerId }] : []
                }
                for (let j = 0; j < this.crmForm.crmFields.length; j++) {
                  const elementJ = this.crmForm.crmFields[j]
                  if (elementJ.key === 'customer_contact_receiver') {
                    if (!isDelect) {
                      elementJ.disabled = false
                      var customerItem = element.value[0]
                      customerItem['moduleType'] = 'customer'
                      // customerItem['customerId'] = item.value[0].customerNameReceiver
                      elementJ['relation'] = customerItem
                    } else {
                      elementJ.disabled = true
                      elementJ['relation'] = {}
                    }
                  }
                }
              }
            }
          }
          if (item.data.formType == 'contract_si') {
            if (typeof item.value == 'string') {
              this.withContract(item.value)
            } else {
              if (item.value.length > 0) {
                this.withContract(item.value[0].num)
              }
            }
          }
        } else if ((this.psiType === 'borrowLeave' || this.psiType === 'retrunEnter' || this.psiType === 'salesLeave') && item.data.formType == 'customer_all') {
          // 新建出入库, 客户名称的选择 关联客户联系人
          for (let index = 0; index < this.crmForm.crmFields.length; index++) {
            const element = this.crmForm.crmFields[index]
            if (element.key === 'customer_contact_receiver') {
              // 如果是商机 改变商机样式和传入客户ID
              if (item.value.length > 0) {
                element.disabled = false
                var customerItem = item.value[0]
                customerItem['moduleType'] = 'customer'
                element['relation'] = customerItem
                element.value = []
              } else {
                element.disabled = true
                element['relation'] = {}
                element.value = ''
              }
            } else if (element.key === 'customer_phone_receiver') {
              // if (item.value.length > 0) {
              //   element.value = item.value[0].mobile
              // } else {
              //   element.value = ''
              // }
              element.value = ''
            }
          }
          // for (let index = 0; index < this.crmForm.crmFields.length; index++) {
          //   const element = this.crmForm.crmFields[index]
          //   if (element.key === 'customer_name_receiver') {
          //     var params = {
          //       customerId: item.value[0].customerId
          //     }
          //     crmCustomerQueryContacts(params)
          //       .then(res => {
          //         for (let indexp = 0; indexp < this.crmForm.crmFields.length; indexp++) {
          //           const elementp = this.crmForm.crmFields[indexp]
          //           if (elementp.key === 'customer_contact_receiver') {
          //             elementp.value = res.data.list[0].name
          //           } else if (elementp.key === 'customer_phone_receiver') {
          //             elementp.value = res.data.list[0].mobile
          //           }
          //         }
          //         this.loading = false
          //       })
          //       .catch(() => {
          //         this.loading = false
          //       })
          //   }
          // }
        } else if (this.psiType === 'retrunEnter') {
          if (item.data.fieldName == 'link_id') {
          }
        } else if (this.psiType === 'testLeave') {
          if (item.data.formType == 'user') {
            for (let index = 0; index < this.crmForm.crmFields.length; index++) {
              const element = this.crmForm.crmFields[index]
              if (element.key === 'customer_phone_receiver') {
                element.value = item.value[0].mobile
              } else if (element.key === 'confirming_user_id') {
                var valueCont = []
                for (var i = 0; i < item.value.length; i++) {
                  valueCont.push({ userId: item.value[i].userId, realname: item.value[i].realname })
                }
                element.value = valueCont
              }
            }
          }
        }
        this.$refs.crmForm.validateField('crmFields.' + data.index + '.value')
      } else if (this.psiType === 'product') { // 进销存的产品模块
        if (item.data.formType == 'storehouse') {
          this.getStorehouse = []
          data.value.forEach(item => {
            this.getStorehouse.push({ 'storehouseId': item.storehouseId, 'storehouseName': item.name, minnumWarn: 0,
              maxnumWarn: 0 })
          })
          this.$refs.crmForm.validateField('crmFields.' + data.index + '.value')
        } else if (item.data.formType == 'select' && item.data.fieldName == 'upc_code_unique_flag') {
          var index = item.data.setting.indexOf(data.value)
          this.upCodeUniqueFlag = index
        } else if (item.data.formType == 'select' && item.data.fieldName == 'product_type') {
          var typeIndex = item.data.setting.indexOf(data.value)
          this.productType = typeIndex
        }
      }
      if (item.data.formType == 'customer_contact_si') {
        if (typeof data.value == 'string') {
          // item.name = this.value
        } else {
          for (let index = 0; index < this.crmForm.crmFields.length; index++) {
            const element = this.crmForm.crmFields[index]
            if (element.key === 'customer_phone_receiver') {
              if (data.value.length > 0) {
                element.value = item.value[0].mobile
              } else {
                element.value = ''
              }
            }
          }
        }
      }
      // 无事件的处理 后期可换成input实现
      if (
        item.data.formType == 'user' ||
        item.data.formType == 'structure' ||
        item.data.formType == 'file' ||
        item.data.formType == 'category' ||
        item.data.formType == 'customer' ||
        item.data.formType == 'business' ||
        item.data.formType == 'contract' ||
        item.data.formType == 'customer_all'
      ) {
        this.$refs.crmForm.validateField('crmFields.' + data.index + '.value')
      }
    },
    // 获取自定义字段
    getField() {
      this.loading = true
      // 获取自定义字段的更新时间
      var params = {
        label: psiTypeModel[this.psiType]
      }
      // // 进行编辑操作
      if (this.action.type == 'update') {
        params.id = this.action.id
      }

      filedGetField(params)
        .then(res => {
          this.getcrmRulesAndModel(res.data)
          this.loading = false
        })
        .catch(() => {
          this.loading = false
        })
    },
    // 根据自定义字段获取自定义字段规则
    getcrmRulesAndModel(list) {
      let showStyleIndex = -1
      for (let index = 0; index < list.length; index++) {
        const item = list[index]
        showStyleIndex += 1
        /**
         * 规则数据
         */

        this.crmRules[item.fieldName] = this.getItemRulesArrayFromItem(item)
        /**
         * 表单数据
         */
        if (
          // crm相关信息特殊处理
          item.formType == 'contacts' ||
          item.formType == 'customer' ||
          item.formType == 'contract' ||
          item.formType == 'business' ||
          item.formType == 'receivables_plan' ||
          item.formType == 'customer_name_receiver' ||
          item.formType == 'psi_salesLeave_si' ||
          item.formType == 'finance_purchase_si' ||
          item.formType == 'psi_borrowLeave_si' ||
          item.formType == 'psi_repairLeave_si' ||
          item.formType == 'psi_testLeave_si' ||
          item.formType == 'psi_otherLeave_si' ||
          item.formType == 'customer_all' ||
          item.formType == 'contract_si'
        ) {
          var params = {}
          params['key'] = item.fieldName
          params['data'] = item
          // 获取 value relative 信息
          this.getParamsValueAndRelativeInfo(params, item, list)
          params['disabled'] = this.getItemDisabledFromItem(item)
          params['styleIndex'] = showStyleIndex
          params['relation'] = {};
          params['relation']['pageType'] = this.psiType;
          if (item.fieldName === 'customer_phone_receiver') {
            if (this.customerValueBiz.length > 0) {
              params.disabled = false
              var customerItem = this.customerValueBiz[0]
              customerItem['moduleType'] = 'customer'
              params['relation'] = customerItem
            } else {
              // params.disabled = true
              // params['relation'] = {}
              // params.value = []
              params['disabled'] = this.getItemDisabledFromItem(item)
              params['styleIndex'] = showStyleIndex
              params['relation'] = {};
              params['relation']['pageType'] = this.crmType;
            }
          }
          this.crmForm.crmFields.push(params)
        } else if (item.formType == 'customer_contact_si') {
          var customerItem = {}
          for (let index = 0; index < this.crmForm.crmFields.length; index++) {
            const element = this.crmForm.crmFields[index]
            if (element.key === 'customer_name_receiver') {
              if (item.value.length > 0) {
                customerItem = element.value[0]
                customerItem['moduleType'] = 'customer'
              } else {
                customerItem = {}
              }
            }
          }
          var params = {}
          params['key'] = item.fieldName
          params['data'] = item
          // 获取 value relative 信息
          this.getParamsValueAndRelativeInfo(params, item, list)
          params['disabled'] = this.getItemDisabledFromItem(item)
          params['styleIndex'] = showStyleIndex
          params['relation'] = customerItem
          params['relation']['pageType'] = this.psiType;
          this.crmForm.crmFields.push(params)
        } else if (item.formType == 'category') {
          /** 产品分类 */
          var params = {}
          params['key'] = item.fieldName
          params['data'] = item
          if (this.action.type == 'update' && item.value) {
            params['value'] = item.value
              ? item.value.map(function(item, index, array) {
                return parseInt(item)
              })
              : []
          } else {
            params['value'] = []
          }
          params['disabled'] = item.isDisabled == 1; // 是否可交互
          params['styleIndex'] = showStyleIndex
          this.crmForm.crmFields.push(params)
        } else if (item.formType == 'product') {
          // 关联产品信息比较多 用字典接收
          var params = {}
          params['value'] = item.value
          params['key'] = item.fieldName
          params['data'] = item
          params['disabled'] = item.isDisabled == 1; // 是否可交互
          params['showblock'] = true // 展示整行效果
          if (index % 2 == 0) {
            showStyleIndex = -1
          }

          // 相关添加 并且商机存在 获取产品
          if (this.action.type == 'relative') {
            const businessData = this.action.data.business
            if (businessData) {
              crmBusinessProduct({
                businessId: businessData.businessId,
                pageType: 0
              })
                .then(res => {
                  params['value'] = {
                    product: res.data.list,
                    totalPrice: res.data.money,
                    discountRate: res.data.discountRate
                  }

                  // 金额赋值 金额必须在产品前面
                  for (
                    let moneyIndex = 0;
                    moneyIndex < this.crmForm.crmFields.length;
                    moneyIndex++
                  ) {
                    const moneyElement = this.crmForm.crmFields[index]
                    if (moneyElement.key === 'money') {
                      moneyElement['value'] = res.data.money
                    }
                  }
                })
                .catch(() => {})
            }
          }
          this.crmForm.crmFields.push(params)
        } else if (item.formType == 'map_address') {
          // 关联产品信息比较多 用字典接收
          var params = {}

          if (this.action.type == 'update') {
            if (item.value.address) {
              item.value.address = item.value.address.split(',')
            }
            params['value'] = item.value // 编辑的值 在value字段
          } else {
            params['value'] = {} // 加入默认值 可能编辑的时候需要调整
          }
          params['key'] = item.fieldName
          params['data'] = item
          params['disabled'] = item.isDisabled == 1; // 是否可交互
          params['showblock'] = true // 展示整行效果
          if (index % 2 == 0) {
            showStyleIndex = -1
          }
          this.crmForm.crmFields.push(params)
        } else if (item.formType == 'picture' || item.formType == 'type_phone') {
          // 关联产品信息比较多 用字典接收
          var params = {}
          if (item.formType == 'type_phone' && item.value != '') {
            params['value'] = item.value && JSON.parse(item.value)
          } else {
            params['value'] = item.value
          }
          params['key'] = item.fieldName
          params['data'] = item
          params['disabled'] = item.isDisabled == 1; // 是否可交互
          params['showblock'] = true // 展示整行效果
          if (index % 2 == 0) {
            showStyleIndex = -1
          }
          this.crmForm.crmFields.push(params)
        } else if (item.formType == 'storehouse') {
          // 关联仓库和电话
          var params = {}

          if (this.action.type == 'update') {
            if (item.value[0] != undefined) {
              this.searchProdutHouseId = item.value[0].storehouseId
            }
            params['value'] = item.value // 编辑的值 在value字段
          } else {
            params['value'] = [] // 加入默认值 可能编辑的时候需要调整
          }
          params['key'] = item.fieldName
          params['data'] = item
          params['styleIndex'] = showStyleIndex
          params['disabled'] = item.isDisabled == 1; // 是否可交互
          this.crmForm.crmFields.push(params)
        } else {
          var params = {}
          if (
            item.formType == 'user' ||
            item.formType == 'structure' ||
            item.formType == 'file' ||
            item.formType == 'category' ||
            item.formType == 'customer' ||
            item.formType == 'business' ||
            item.formType == 'contract' ||
            item.formType == 'pictures'
          ) {
            if (this.action.type == 'update') {
              if (item.formType == 'pictures' && item.value) {
                item.value = JSON.parse(item.value)
              }
              params['value'] = item.value ? objDeepCopy(item.value) : []
            } else {
              if (this.isenter && item.formType == 'user') {
                var userData = [{
                  realname: this.userInfo.realname,
                  userId: this.userInfo.userId
                }]
                params['value'] = userData
              } else if (this.isLeave && (item.fieldName == 'confirming_user_id' || (item.fieldName == 'customer_name_receiver' && item.formType == 'user'))) {
                var userData = [{
                  realname: this.userInfo.realname,
                  userId: this.userInfo.userId
                }]
                params['value'] = userData
              } else {
                params['value'] = item.defaultValue
                  ? objDeepCopy(item.defaultValue)
                  : []
              }
            }
          } else {
            if (this.action.type == 'update') {
              if (item.formType == 'select' && (item.fieldName == 'upc_code_unique_flag' || item.fieldName == 'product_type')) {
                params['value'] = item.setting[item.value]
              } else {
                params['value'] = item.value || '' // 编辑的值 在value∂ç字段
              }
            } else {
              if (item.value != '' && item.fieldName == 'els_num') {
                params['value'] = item.value
              } else if (item.fieldName == 'els_date') {
                var datetime = this.getdate(new Date())
                params['value'] = datetime
              } else {
                params['value'] = item.defaultValue || ''
              }
            }
          }

          params['key'] = item.fieldName
          params['data'] = item
          params['disabled'] = item.isDisabled == 1; // 是否可交互
          params['styleIndex'] = showStyleIndex
          this.crmForm.crmFields.push(params)
        }
      }
    },
    /**
     * 获取关联项的值 和 关联信息
     */
    getParamsValueAndRelativeInfo(params, item, list) {
      if (this.action.type == 'relative') {
        const relativeData = this.action.data[item.formType]
        if (item.formType == 'receivables_plan') {
          params['value'] = ''
        } else {
          params['value'] = relativeData ? [relativeData] : []
          if (item.formType === 'customer') {
            this.customerValueBiz = relativeData ? [relativeData] : []
          }
        }
      } else {
        if (item.formType == 'receivables_plan') {
          params['value'] = item.value || ''
        } else {
          params['value'] = item.value || []
          if (item.formType === 'customer_all') {
            this.customerValueBiz = item.value || []
          }
        }
      }
      if (this.action.type == 'relative' || this.action.type == 'update') {
        // 回款计划 需要合同信息
        if (item.formType === 'receivables_plan') {
          const contractItem = this.getItemRelatveInfo(item, list, 'contract')
          if (contractItem) {
            contractItem['moduleType'] = 'contract'
            params['relation'] = contractItem
          }
          // 商机合同 需要客户信息
        } else if (item.formType == 'business' || item.formType == 'contract') {
          const customerItem = this.getItemRelatveInfo(item, list, 'customer')
          if (item.formType == 'business' && customerItem) {
            customerItem['moduleType'] = 'customer'
            params['relation'] = customerItem
          } else if (item.formType == 'contract' && customerItem) {
            customerItem['moduleType'] = 'customer'
            customerItem['params'] = { checkStatus: 1 }
            params['relation'] = customerItem
          }
        }
      }
    },
    /**
     * 获取相关联item
     */
    getItemRelatveInfo(item, list, fromType) {
      let crmItem = null
      if (this.action.type == 'relative') {
        crmItem = this.action.data[fromType]
      } else {
        const crmObj = list.find(listItem => {
          return listItem.formType === fromType
        })
        if (crmObj && crmObj.value && crmObj.value.length > 0) {
          crmItem = crmObj.value[0]
        }
      }
      return crmItem
    },
    /**
     * 获取关联项是否可操作
     */
    getItemDisabledFromItem(item) {
      // 相关添加
      if (this.action.type == 'relative') {
        const relativeDisInfos = {
          business: {
            customer: { customer: true },
            contacts: { customer: true }
          },
          contacts: {
            customer: { customer: true },
            business: { customer: true }
          },
          contract: {
            customer: { customer: true },
            business: { customer: true, business: true }
          },
          receivables_plan: {
            contract: { customer: true, contract: true },
            customer: { customer: true }
          },
          receivables: {
            contract: { customer: true, contract: true },
            customer: { customer: true }
          },
          preSales: {
            business: {business: true}
          }
        }
        // 添加类型
        const psiTypeDisInfos = relativeDisInfos[this.psiType]
        if (psiTypeDisInfos) {
          // 在哪个类型下添加
          const relativeTypeDisInfos = psiTypeDisInfos[this.action.psiType]
          if (relativeTypeDisInfos) {
            // 包含的字段值
            return relativeTypeDisInfos[item.formType] || false
          }
        }
        return item.isDisabled == 1;
      } else if (this.action.type != 'update') {
        // 新建
        if (this.psiType === 'contract' && item.formType === 'business') {
          return true
          // 回款下 新建 合同 和 回款计划 默认不能操作
        } else if (this.psiType === 'receivables') {
          if (item.formType === 'contract') {
            return true
          } else if (item.formType === 'receivables_plan') {
            return true
          }
        } else if (this.psiType === 'retrunEnter' || this.psiType === 'salesLeave') { // 归还入库下的客户名称和联系人
          if (item.formType === 'customer_contact_si' && item.fieldName === 'customer_contact_receiver') {
            return true
          }
        }
      } else if (this.action.type == 'update'){
        const relativeDisInfos = {
          preSales: {
            business: { business: true }
          }
        }
        // 添加类型
        const psiTypeDisInfos = relativeDisInfos[this.psiType]
        if (psiTypeDisInfos) {
          // 在哪个类型下添加
          const relativeTypeDisInfos = psiTypeDisInfos[this.action.psiType]
          if (relativeTypeDisInfos) {
            // 包含的字段值
            return relativeTypeDisInfos[item.formType] || false
          }
        }
        return item.isDisabled == 1;
      }
      return item.isDisabled == 1;
    },
    /**
     * item 当行数据源
     */
    getItemRulesArrayFromItem(item) {
      var tempList = []
      // 验证必填
      if (item.isNull == 1) {
        if (item.formType == 'category') {
          tempList.push({
            required: true,
            message: item.name + '不能为空',
            trigger: []
          })
        } else {
          tempList.push({
            required: true,
            message: item.name + '不能为空',
            trigger: ['blur', 'change']
          })
        }
      }

      // 验证唯一
      if (item.isUnique == 1) {
        var validateUnique = (rule, value, callback) => {
          if ((isArray(value) && value.length == 0) || !value) {
            callback()
          } else {
            var validatesParams = {}
            validatesParams.fieldId = item.fieldId
            if (isArray(value)) {
              let postValue = ''
              if (value.length > 0) {
                if (
                  rule.item.formType == 'user' ||
                  rule.item.formType == 'structure'
                ) {
                  postValue = value
                    .map(valueItem => {
                      return rule.item.formType == 'user'
                        ? valueItem.userId
                        : valueItem.id
                    })
                    .join(',')
                } else if (rule.item.fieldName == 'categoryId') {
                  if (value && value.length) {
                    postValue = value[value.length - 1]
                  } else {
                    postValue = ''
                  }
                } else if (rule.item.formType == 'checkbox') {
                  postValue = value.join(',')
                }
              }
              validatesParams.value = postValue
            } else {
              validatesParams.value = value
            }
            if (this.action.type == 'update') {
              validatesParams.batchId = this.action.batchId
            }
            filedValidates(validatesParams)
              .then(res => {
                callback()
              })
              .catch(error => {
                this.showBtnCheck = true
                callback(new Error(error.msg ? error.msg : '验证出错'))
              })
          }
        }
        tempList.push({
          validator: validateUnique,
          item: item,
          trigger:
            item.formType == 'checkbox' || item.formType == 'select'
              ? ['change']
              : ['blur']
        })
      }

      // 特殊字符
      if (item.formType == 'number') {
        var validateCRMNumber = (rule, value, callback) => {
          if (!value || value == '' || regexIsCRMNumber(value)) {
            callback()
          } else {
            callback(new Error('数字的整数部分须少于12位，小数部分须少于4位'))
          }
        }
        tempList.push({
          validator: validateCRMNumber,
          item: item,
          trigger: ['blur']
        })
      } else if (item.formType == 'floatnumber') {
        var validateCRMMoneyNumber = (rule, value, callback) => {
          if (!value || value == '' || regexIsCRMMoneyNumber(value)) {
            callback()
          } else {
            callback(new Error('货币的整数部分须少于10位，小数部分须少于2位'))
          }
        }
        tempList.push({
          validator: validateCRMMoneyNumber,
          item: item,
          trigger: ['blur']
        })
      } else if (item.formType == 'mobile') {
        var validateCRMMobile = (rule, value, callback) => {
          if (!value || value == '' || regexIsCRMMobile(value)) {
            callback()
          } else {
            callback(new Error('手机格式有误'))
          }
        }
        tempList.push({
          validator: validateCRMMobile,
          item: item,
          trigger: ['blur']
        })
      } else if (item.formType == 'email') {
        var validateCRMEmail = (rule, value, callback) => {
          if (!value || value == '' || regexIsCRMEmail(value)) {
            callback()
          } else {
            callback(new Error('邮箱格式有误'))
          }
        }
        tempList.push({
          validator: validateCRMEmail,
          item: item,
          trigger: ['blur']
        })
      }
      return tempList
    },
    // 保存草稿
    saveDraftField() {
      this.saveField(false, true)
    },
    // 保存数据
    saveField(saveAndCreate, isDraft = false) {
      this.saveAndCreate = saveAndCreate
      this.$refs.crmForm.validate(valid => {
        if (valid) {
          if (this.showExamine) {
            /** 验证审批数据 */
            if (isDraft) {
              // 不验证数据
              var params = this.getSubmiteParams(this.crmForm.crmFields)
              if (
                this.examineInfo.examineType === 2 &&
                this.examineInfo.hasOwnProperty('value') &&
                this.examineInfo.value.length
              ) {
                params['checkUserId'] = this.examineInfo.value[0].userId
              }
              params.entity.checkStatus = 5
              if (this.isenter || this.isLeave) {
                if (this.action.type == 'update') {
                  params.entity.elsId = this.action.elsId
                }
                params.entity.label = psiTypeModel[this.psiType]
                var productData = JSON.parse(JSON.stringify(this.$refs.storeProductCom.ruleForm.tableData))
                var newProduct = []
                var isPass = []
                for (var j = 0; j < productData.length; j++) {
                  // 验证是否有产品开始
                  if (productData[j].productId == '' || productData[j].productId == null) {
                    this.$message.error('请添加出入库的产品')
                    productData[j].productId = null
                    return false
                  } else {
                    // 在入库的时候，若是主产品，必须验证产品条码
                    if (this.isenter) {
                      var codeIsPass = []
                      if (productData[j].upcCodeUniqueFlag == 1) {
                        for (var code = 0; code < productData[j].upcCode.length; code++) {
                          if (productData[j].upcCode[code].barcode == '' || productData[j].upcCode[code].barcode == undefined || productData[j].upcCode[code].barcode == null) {
                            this.$message.error('请录入产品条码')
                            productData[j].upcCode[code].barcode = null
                            return false
                          } else {
                            codeIsPass.push(true)
                          }
                        }
                        if (codeIsPass.length == productData[j].upcCode.length) {
                          isPass.push(true)
                        }
                      } else {
                        isPass.push(true)
                      }
                    } else { // 出库
                      isPass.push(true)
                    }
                  }
                  // 验证是否有产品结束
                }
                if (isPass.length == productData.length) {
                  for (var j = 0; j < productData.length; j++) {
                    productData[j].elsQuantity = Number(productData[j].elsQuantity)
                    if (productData[j].upcCode.length > 1) {
                      for (var i = 0; i < productData[j].upcCode.length; i++) {
                        var itemProduct = JSON.parse(JSON.stringify(productData[j]))
                        itemProduct.upcCode = ''
                        itemProduct.upcCode = productData[j].upcCode[i].barcode
                        itemProduct.elsQuantity = 1
                        newProduct.push(itemProduct)
                      }
                    } else {
                      if (productData[j].upcCode[0].barcode != '') {
                        productData[j].upcCode = productData[j].upcCode[0].barcode
                      } else {
                        productData[j].upcCode = ''
                      }
                      newProduct.push(productData[j])
                    }
                    delete productData[j].productNameData
                  }
                  params['products'] = newProduct
                  this.submiteParams(params)
                }
              } else {
                this.submiteParams(params)
              }
            } else {
              this.$refs.examineInfo.validateField(() => {
                var params = this.getSubmiteParams(this.crmForm.crmFields)
                if (this.examineInfo.examineType === 2) {
                  params['checkUserId'] = this.examineInfo.value[0].userId
                }
                if (this.isenter || this.isLeave) {
                  if (this.action.type == 'update') {
                    params.entity.elsId = this.action.elsId
                  }
                  params.entity.label = psiTypeModel[this.psiType]
                  var productData = JSON.parse(JSON.stringify(this.$refs.storeProductCom.ruleForm.tableData))
                  var newProduct = []
                  var isPass = []
                  for (var j = 0; j < productData.length; j++) {
                    // 验证是否有产品开始
                    if (productData[j].productId == '' || productData[j].productId == null) {
                      this.$message.error('请添加出入库的产品')
                      productData[j].productId = null
                      return false
                    } else {
                      // 在入库的时候，若是主产品，必须验证产品条码
                      if (this.isenter) {
                        var codeIsPass = []
                        if (productData[j].upcCodeUniqueFlag == 1) {
                          for (var code = 0; code < productData[j].upcCode.length; code++) {
                            if (productData[j].upcCode[code].barcode == '' || productData[j].upcCode[code].barcode == undefined || productData[j].upcCode[code].barcode == null) {
                              this.$message.error('请录入产品条码')
                              productData[j].upcCode[code].barcode = null
                              return false
                            } else {
                              codeIsPass.push(true)
                            }
                          }
                          if (codeIsPass.length == productData[j].upcCode.length) {
                            isPass.push(true)
                          }
                        } else {
                          isPass.push(true)
                        }
                      } else { // 出库
                        isPass.push(true)
                      }
                    }
                    // 验证是否有产品结束
                  }
                  if (isPass.length == productData.length) {
                    for (var j = 0; j < productData.length; j++) {
                      productData[j].elsQuantity = Number(productData[j].elsQuantity)
                      if (productData[j].upcCode.length > 1) {
                        for (var i = 0; i < productData[j].upcCode.length; i++) {
                          var itemProduct = JSON.parse(JSON.stringify(productData[j]))
                          itemProduct.upcCode = ''
                          itemProduct.upcCode = productData[j].upcCode[i].barcode
                          itemProduct.elsQuantity = 1
                          newProduct.push(itemProduct)
                        }
                      } else {
                        if (productData[j].upcCode[0].barcode != '') {
                          productData[j].upcCode = productData[j].upcCode[0].barcode
                        } else {
                          productData[j].upcCode = ''
                        }
                        newProduct.push(productData[j])
                      }
                      delete productData[j].productNameData
                    }
                    params['products'] = newProduct
                    this.submiteParams(params)
                  }
                } else {
                  this.submiteParams(params)
                }
              })
            }
          } else if (this.psiType == 'product') {
            this.$refs.moreSpec.validateField(() => {
              var params = this.getSubmiteParams(this.crmForm.crmFields)
              if (this.action.type == 'update') {
                params.entity.productId = this.action.productId
              }
              params['spec'] = this.$refs.moreSpec.ruleForm
              params.entity.upc_code_unique_flag = this.upCodeUniqueFlag
              params.entity.product_type = this.productType
              this.submiteParams(params)
            })
          } else {
            var params = this.getSubmiteParams(this.crmForm.crmFields)
            // if (this.psiType === 'customer' && (params.entity.customer_contacts == undefined || params.entity.customer_contacts.length === 0)) {
            //   this.$message.error('请添加联系人')
            //   return
            // }
            if (this.action.type == 'update') {
              params.entity[this.psiType + 'Id'] = this.action[this.psiType + 'Id']
            }
            this.submiteParams(params)
          }
        } else {
          return false
        }
      })
    },
    /** 上传 */
    submiteParams(params) {
      this.loading = true
      var crmRequest = this.getSubmiteRequest()
      if (this.action.type == 'update') {
        const key = this.psiType == 'receivables_plan' ? 'plan' : this.psiType
        if (this.psiType == 'leads') {
          params.entity['customerId'] = this.action.id
        } else {
          params.entity[key + 'Id'] = this.action.id
        }
        params.entity.batchId = this.action.batchId
      }

      // 相关添加时候的多余提交信息
      if (
        this.action.relativeData &&
        Object.keys(this.action.relativeData).length
      ) {
        params = { ...params, ...this.action.relativeData }
      }
      crmRequest(params)
        .then(res => {
          this.loading = false
          if (this.psiType == 'customer') {
            if (!this.saveAndCreate) {
              this.$message.success(
                this.action.type == 'update' ? '编辑成功' : '添加成功'
              )
              this.hidenView()
            }
          } else {
            this.hidenView()
            this.$message.success(
              this.action.type == 'update' ? '编辑成功' : '添加成功'
            )
          }
          // 回到保存成功
          this.$emit('save-success', {
            type: this.psiType,
            data: res.data || {},
            saveAndCreate: this.saveAndCreate
          })
        })
        .catch(() => {
          this.loading = false
        })
    },
    /** 获取上传url */
    getSubmiteRequest() {
      if (this.psiType == 'storehouse') {
        return psiStorehouseSave
      } else if (this.psiType == 'product') {
        return psiProductSave
      } else if (this.isenter || this.isLeave) {
        return psiEnterLeaveStockSave
      }
    },
    /** 拼接上传传输 */
    getSubmiteParams(array) {
      var params = { entity: {}, field: [] }
      for (let index = 0; index < array.length; index++) {
        const element = array[index]
        if (element.key == 'material') {
          this.getProductParams(params, element)
        } else if (element.key == 'map_address') {
          this.getCustomerAddressParams(params.entity, element)
        } else if (element.key == 'customer_contact_receiver' && element.data.formType == 'customer_contact_si') {
          this.getCustomerContactSiParams(params.entity, element)
        } else if (element.key == 'customer_contacts') {
          params.entity[element.key] = element.value
        } else if (element.data.fieldType == 1) {
          params.entity[element.key] = this.getRealParams(element) || ''
        } else {
          element.data.value = this.getRealParams(element)
          params.field.push(element.data)
        }
      }
      return params
    },
    getProductParams(params, element) {
      if (element.value) {
        params['material'] = element.value.product ? element.value.product : []
        params.entity['totalPrice'] = element.value.totalPrice
          ? element.value.totalPrice
          : 0
        params.entity['discountRate'] = element.value.discountRate
          ? element.value.discountRate
          : 0
      } else {
        params['material'] = []
        params.entity['totalPrice'] = ''
        params.entity['discountRate'] = ''
      }
    },
    // 获取客户位置参数
    getCustomerAddressParams(params, element) {
      params['address'] = element.value.address
        ? element.value.address.join(',')
        : ''
      params['detailAddress'] = element.value.detailAddress
      params['location'] = element.value.location
      params['lng'] = element.value.lng
      params['lat'] = element.value.lat
    },
    // 可选择和可输入的联系人
    getCustomerContactSiParams(params, element) {
      if (typeof element.value == 'string') {
        params['customer_contact_receiver'] = element.value
        params['customer_contact_id_receiver'] = ''
      } else {
        params['customer_contact_receiver'] = element.value[0].name
        params['customer_contact_id_receiver'] = element.value[0].contactsId
      }
    },
    // 关联客户 联系人等数据要特殊处理
    getRealParams(element) {
      if (
        element.key == 'customer_id' ||
        element.key == 'contacts_id' ||
        element.key == 'business_id' ||
        element.key == 'leads_id' ||
        element.key == 'contract_id'
      ) {
        if (element.value && element.value.length) {
          const key = element.key.replace('_id', 'Id')
          return element.value[0][key]
        } else {
          return ''
        }
      } else if (
        element.data.formType == 'user' ||
        element.data.formType == 'structure'
      ) {
        return element.value
          .map(function(item, index, array) {
            return element.data.formType == 'user' ? item.userId : item.id
          })
          .join(',')
      } else if (element.data.formType == 'file') {
        if (element.value && element.value.length > 0) {
          return element.value[0].batchId
        }
        return ''
      } else if (element.key == 'category_id') {
        if (element.value && element.value.length > 0) {
          return element.value[element.value.length - 1]
        }
        return ''
      } else if (element.data.formType == 'checkbox') {
        if (element.value && element.value.length > 0) {
          return element.value.join(',')
        }
        return ''
      } else if (element.data.formType == 'storehouse') {
        return element.value
          .map(function(item, index, array) {
            return item.storehouseId
          })
          .join(',')
      } else if (element.key == 'object_id') {
        var self = this
        if ((this.isenter || this.isLeave) && element.data.formType != 'text') {
          return element.value
            .map(function(item, index, array) {
              if (
                self.psiType == 'salesEnter' ||
                self.psiType == 'salesLeave'
              ) {
                return item.customerId
              } else if (
                self.psiType == 'purchaseEnter' ||
                self.psiType == 'repairEnter' ||
                self.psiType == 'repairLeave'
              ) {
                return item.supplierId
              }
            })
            .join(',')
        } else {
          return element.value
        }
      } else if (this.isLeave || this.isenter) {
        if (element.key == 'customer_name_receiver') {
          if (element.data.formType === 'supplier') {
            return element.value
              .map(function(item, index, array) {
                return item.supplierId
              })
              .join(',')
          } else if (element.data.formType === 'customer_all') {
            return element.value
              .map(function(item, index, array) {
                return item.customerId
              })
              .join(',')
          } else if (element.data.formType === 'user') {
            return element.value
              .map(function(item, index, array) {
                return item.userId
              })
              .join(',')
          }
        } else if (element.key == 'link_id') {
          if (element.data.formType === 'contract_si') {
            if (typeof element.value == 'string') {
              return element.value
            } else {
              return element.value
                .map(function(item, index, array) {
                  return item.num
                })
                .join(',')
            }
          } else if (
            element.data.formType === 'psi_salesLeave_si' ||
            element.data.formType === 'finance_purchase_si' ||
            element.data.formType === 'psi_borrowLeave_si' ||
            element.data.formType === 'psi_repairLeave_si' ||
            element.data.formType === 'psi_testLeave_si' ||
            element.data.formType === 'psi_otherLeave_si'
          ) {
            if (typeof element.value == 'string') {
              return element.value
            } else {
              return element.value
                .map(function(item, index, array) {
                  return element.data.formType === 'finance_purchase_si' ? item.purchaseNum : item.elsNum
                })
                .join(',')
            }
          }
        }
      }

      return element.value
    },
    hidenView() {
      this.$emit('hiden-view')
    },
    // 根据类型获取标题展示名称
    getTitle() {
      if (this.psiType == 'product') {
        return this.action.type == 'update' ? '编辑产品' : '新建产品'
      } else if (this.psiType == 'storehouse') {
        return this.action.type == 'update' ? '编辑仓库' : '新建仓库'
      } else if (this.psiType == 'salesEnter') {
        return this.action.type == 'update' ? '编辑销售退货' : '新建销售退货'
      } else if (this.psiType == 'retrunEnter') {
        return this.action.type == 'update' ? '编辑归还入库' : '新建归还入库'
      } else if (this.psiType == 'repairEnter') {
        return this.action.type == 'update' ? '编辑维修入库' : '新建维修入库'
      } else if (this.psiType == 'testEnter') {
        return this.action.type == 'update' ? '编辑内部测试入库' : '新建内部测试入库'
      } else if (this.psiType == 'inventoryProfitEnter') {
        return this.action.type == 'update' ? '编辑盘盈' : '新建盘盈'
      } else if (this.psiType == 'otherEnter') {
        return this.action.type == 'update' ? '编辑其他入库' : '新建其他入库'
      } else if (this.psiType == 'purchaseEnter') {
        return this.action.type == 'update' ? '编辑采购入库' : '新建采购入库'
      } else if (this.psiType == 'salesLeave') {
        return this.action.type == 'update' ? '编辑销售出库' : '新建销售出库'
      } else if (this.psiType == 'borrowLeave') {
        return this.action.type == 'update' ? '编辑借用出库' : '新建借用出库'
      } else if (this.psiType == 'repairLeave') {
        return this.action.type == 'update' ? '编辑维修出库' : '新建维修出库'
      } else if (this.psiType == 'testLeave') {
        return this.action.type == 'update' ? '编辑内部测试出库' : '新建内部测试出库'
      } else if (this.psiType == 'inventoryLossLeave') {
        return this.action.type == 'update' ? '编辑盘亏' : '新建盘亏'
      } else if (this.psiType == 'otherLeave') {
        return this.action.type == 'update' ? '编辑其他出库' : '新建其他出库'
      }
    },
    // 获取左边padding
    getPaddingLeft(item, index) {
      if (item.showblock && item.showblock == true) {
        return '0'
      }
      return item.styleIndex % 2 == 0 ? '0' : '25px'
    },
    // 获取左边padding
    getPaddingRight(item, index) {
      if (item.showblock && item.showblock == true) {
        return '0'
      }

      return item.styleIndex % 2 == 0 ? '25px' : '0'
    },
    // 获取当前的标准时间
    getdate(date) {
      var year = date.getFullYear()
      var month = date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1
      var day =
        date.getDate() < 10 ? '0' + date.getDate() : date.getDate()
      var hours =
        date.getHours() < 10 ? '0' + date.getHours() : date.getHours()
      var minutes =
        date.getMinutes() < 10 ? '0' + date.getMinutes() : date.getMinutes()
      var seconds =
        date.getSeconds() < 10 ? '0' + date.getSeconds() : date.getSeconds()
      var time = year +
        '-' +
        month +
        '-' +
        day +
        ' ' +
        hours +
        ':' +
        minutes +
        ':' +
        seconds
      return time
    }
  }
}
</script>
<style lang="scss" scoped>
  .crm-create-container {
    position: relative;
    height: 100%;
  }

  .crm-create-flex {
    position: relative;
    overflow-x: hidden;
    overflow-y: auto;
    flex: 1;
  }

  .crm-create-header {
    height: 40px;
    margin-bottom: 20px;
    padding: 0 10px;
    flex-shrink: 0;
    .close {
      display: block;
      width: 40px;
      height: 40px;
      margin-right: -10px;
      padding: 10px;
      cursor: pointer;
    }
  }

  .crm-create-body {
    flex: 1;
    overflow-x: hidden;
    overflow-y: auto;
  }

  /** 将其改变为flex布局 */
  .crm-create-box {
    display: flex;
    flex-wrap: wrap;
    padding: 0 10px;
  }

  .crm-create-item {
    flex: 0 0 50%;
    flex-shrink: 0;
    // overflow: hidden;
    padding-bottom: 10px;
  }

  // 占用一整行
  .crm-create-block-item {
    flex: 0 0 100%;
    flex-shrink: 0;
    padding-bottom: 10px;
  }

  .el-form-item /deep/ .el-form-item__label {
    line-height: normal;
    font-size: 13px;
    color: #333333;
    position: relative;
    padding-left: 8px;
    padding-bottom: 0;
  }

  .el-form /deep/ .el-form-item {
    margin-bottom: 0px;
  }

  .el-form /deep/ .el-form-item.is-required .el-form-item__label:before {
    content: '*';
    color: #f56c6c;
    margin-right: 4px;
    position: absolute;
    left: 0;
    top: 5px;
  }

  .handle-bar {
    position: relative;
    .handle-button {
      float: right;
      margin-top: 5px;
      margin-right: 20px;
    }
  }

  .el-button + .el-button {
    margin-left: 0;
  }

  // 审核信息 里的审核类型
  .examine-type {
    font-size: 12px;
    color: white;
    background-color: #fd715a;
    padding: 0 8px;
    margin-left: 5px;
    height: 16px;
    line-height: 16px;
    border-radius: 8px;
    transform: scale(0.8, 0.8);
  }
  /*查重信息*/
  .showBtnCheck {
    margin-left: -3px;
    color: blue;
  }
</style>

